package com.gao.service.impl;

import java.sql.SQLException;
import java.util.List;

import com.gao.dao.CartDao;
import com.gao.dao.impl.CartDaoImpl;
import com.gao.domain.Cart;
import com.gao.domain.Product;
import com.gao.domain.User;
import com.gao.service.CartService;
import com.gao.service.ProductService;

public class CartServiceImpl implements CartService{
	CartDao  cartDao = new CartDaoImpl();
	
	@Override
	public boolean add(Cart cart) {
		try {
			return cartDao.insert(cart);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public List<Cart> getCartsByUid(int uid) {
		try {
			List<Cart> carts = cartDao.getCartsByUid(uid);
			//ע�⣺product��Ϣ����������Ҫ�����ݿ��н��е�ȡ���µļ۸���Ϣ
			for(Cart cart:carts){
				int pid = cart.getProduct().getPid();
				ProductService productService  = new ProductServiceImpl();
				Product product = productService.findProductById(pid);
				cart.setProduct(product);
			}
			return carts;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public boolean deleteByCid(int cid) {
		try {
			return cartDao.deleteByCid(cid);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public Cart get(int pid, int uid) {
		try {
			return cartDao.get(pid, uid);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public boolean updateNumber(int increment, int pid, int uid) {
		try {
			return cartDao.updateNumber(increment, pid, uid);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public void addOrUpdateNumber(int increment, int pid, int uid) {
		Cart cart = get(pid, uid);
        try {
			if (cart != null) {
			    //���ﳵ��Ʒ����
			    cartDao.updateNumber(increment, pid, uid);
			} else {
			    //���ﳵ��Ʒ������
			    Cart newCart = new Cart(new Product(pid),increment,new User(uid));
			    cartDao.insert(newCart);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}

	@Override
	public Cart getByCid(int cid) {
		try {
			return cartDao.getByCid(cid);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

}
